package com.njuptB180316.boki.controller;

import com.njuptB180316.boki.dao.BookMapper;
import com.njuptB180316.boki.dao.RecordMapper;
import com.njuptB180316.boki.dao.UserMapper;
import com.njuptB180316.boki.dataobject.Book;
import com.njuptB180316.boki.dataobject.Record;
import com.njuptB180316.boki.dataobject.User;
import com.njuptB180316.boki.interceptor.NeedLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class MybokiController {

    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private RecordMapper recordMapper;

    @NeedLogin
    @RequestMapping("/borrow")
    public String borrow(@RequestParam("bid") String bookId, HttpServletRequest request){
        //点击借书，书数量减一
        Book newBook = bookMapper.selectByPrimaryKey(Integer.parseInt(bookId));
        newBook.setNum(newBook.getNum()-1);
        bookMapper.updateByPrimaryKey(newBook);
        //添加借书记录
        Record record = new Record();
        User user = (User)request.getSession().getAttribute("user");
        record.setPhone(user.getPhone());
        record.setGmtCreated(System.currentTimeMillis());
        record.setId(Integer.parseInt(bookId));
        recordMapper.insert(record);
        return "redirect:/?flag=1";
    }

    @NeedLogin
    @RequestMapping("/returnBook")
    public String returnBook(@RequestParam("bid") String bookId,
                             @RequestParam("btime") String bookTime,
                             HttpServletRequest request){
        //点击还书，书数量加1
        Book returnedBook = bookMapper.selectByPrimaryKey(Integer.parseInt(bookId));
        returnedBook.setNum(returnedBook.getNum()+1);
        bookMapper.updateByPrimaryKey(returnedBook);
        //删除借书记录
        User user = (User)request.getSession().getAttribute("user");
        recordMapper.delete(user.getPhone(), Long.parseLong(bookTime));
        return "redirect:/myboki";
    }

    @NeedLogin
    @RequestMapping("/myboki")
    public String userBorrowRecord(ModelMap modelMap, HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        List<Record> records = recordMapper.selectByPhone(user.getPhone());
        modelMap.addAttribute("records", records);
        return "myboki";
    }
}
